package com.myRule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class TestRule extends AbstractLoadBalancerRule {

    /**
     * 每个服务访问三次，轮询
     */
    private int total = 0;      //服务被调用的次数
    private int index = 0;      //代表当前服务的下标

    public TestRule() {
    }

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();     //获取 活着 的服务
                List<Server> allList = lb.getAllServers();          //获取 全部 的服务

                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

//                int index = this.chooseRandomInt(serverCount);
//                server = (Server)upList.get(index);

        //==============================================自定义部分
                if(total < 2){      //从0开始
                    server = (Server)upList.get(index);
                    total++;
                }else {
                    total = 0;
                    index++;
                    if (index >= upList.size()){
                        index = 0;
                    }
                    server = (Server)upList.get(index);
                }

        //==============================================

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
